﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Net.Mail;
using System.Collections;
using EZCRS.HCMS.Entity;

using CommonMD5 = Common;

namespace EZCRS.HCMS.DataAcl
{
    /// <summary>
    /// 常用公共方法
    /// </summary>
    public class CFun
    {
        public CFun()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        #region MD5
        /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string MD5(string str)
        {
            byte[] b = Encoding.Default.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
            return ret;
        }
        #endregion

        /// <summary>
        /// 使用Common.DLL进行MD5加密
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5加密后的字符串</returns>
        public static string UseDllToMD5(string str) {
            string MD5Encode = CommonMD5.CommonWeb.ToMD5(str);
            return MD5Encode;
        }

        #region des加解密相关
        /// <summary>
        /// cookie 密钥
        /// </summary>
        public static string CookieKey = "andyyang";//cookie加密，可以更改
        public static string BackKey = "hcmsyang";//后台加密，不可更改

        //des加密数据 string sKey   8位
        /// <summary>
        /// des加密
        /// </summary>
        /// <param name="pToEncrypt">需要加密的明文</param>
        /// <param name="sKey">6位密钥</param>
        /// <returns>密文字符串</returns>
        public static string DESEncrypt(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            //把字符串放到byte数组中  
            //原来使用的UTF8编码，我改成Unicode编码了，不行  
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);


            //建立加密对象的密钥和偏移量  
            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法  
            //使得输入密码必须输入英文文本  
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        //des解密方法  
        /// <summary>
        /// des解密函数
        /// </summary>
        /// <param name="pToDecrypt">加密字符串</param>
        /// <param name="sKey">6位密钥</param>
        /// <returns>明文</returns>
        public static string DESDecrypt(string pToDecrypt, string sKey)
        {

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            //建立加密对象的密钥和偏移量，此值重要，不能修改  
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            //建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象  
            StringBuilder ret = new StringBuilder();

            return System.Text.Encoding.Default.GetString(ms.ToArray());

        }
        #endregion

        #region  登录用户信息相关
        /// <summary>
        /// 用户登录名
        /// </summary>
        /// <returns></returns>
        public static string UserName()
        {
            try
            {
                return System.Web.HttpContext.Current.Request.Cookies["hcms"].Values["_username"];
            }
            catch
            {
                return "";
            }
        }
        public static string HotelId()
        {
            try
            {
                return System.Web.HttpContext.Current.Request.Cookies["hcms"].Values["_Pid"];
            }
            catch
            {
                return "0";
            }
        }
        public static string UserId()
        {
            try
            {
                return System.Web.HttpContext.Current.Request.Cookies["hcms"].Values["_userid"];
            }
            catch
            {
                return "0";
            }
        }
        public static string ModuleId()
        {
            try
            {
                return System.Web.HttpContext.Current.Request.Cookies["hcms"].Values["_moduid"];
            }
            catch
            {
                return "0";
            }
        }
        #endregion

        #region 分页相关
        /// <summary>
        /// 根据数据总数和每页数据数计算页数
        /// </summary>
        /// <param name="PageSize">每页数据数</param>
        /// <param name="RecordCount">数据总量</param>
        /// <returns></returns>
        public static int PageCount(int PageSize, int RecordCount)
        {
            if (RecordCount % PageSize > 0)
                return RecordCount / PageSize + 1;
            else
                return RecordCount / PageSize;
        }


        #endregion

        #region 脚本警告窗口
        /// <summary>
        /// 弹出警告窗口
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Types">back：返回   non：无任何动作 </param>
        public static string AlertMeg(string msg, string Types, string urls)
        {
            string str = "<script language=javascript>";
            str += "alert('" + msg + "');";
            if (urls != "")
            {
                str += "location.href='" + urls + "';";
            }
            else
            {
                if (Types == "back")
                {
                    str += "history.go(-1);";
                }
            }
            str += "</script>";

            return str;
        }
        #endregion

        #region 字符相关操作
        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <returns></returns>
        public static int GetStringLength(string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        //截取一定长度字符串，长度为字节长度
        /// <summary>
        /// 截取定长度的字符串
        /// </summary>
        /// <param name="inputString">原字符串</param>
        /// <param name="len">需要截取的长度（一个中文汉字长度为2）</param>
        /// <returns></returns>
        public static string CutStr(string inputString, int len)
        {
            #region
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            inputString = inputString.ToLower();
            byte[] s = ascii.GetBytes(inputString);

            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
                try
                {
                    tempString += inputString.Substring(i, 1);
                }
                catch
                {
                    break;
                }
                if (tempLen > len)
                {
                    break;
                }
            }
            byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
            if (mybyte.Length > len)
            {
                tempString += "..";
            }
            return tempString;
            #endregion
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent">要分割的内容</param>
        /// <param name="strSplit">分割字符串</param>
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (strContent.IndexOf(strSplit) < 0)
            {
                string[] tmp = { strContent };
                return tmp;
            }
            return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(string content)
        {
            string regexstr = @"<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 转换为简体中文
        /// </summary>
        //public static string ToSChinese(string str)
        //{
        //    return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0);
        //}

        /// <summary>
        /// 转换为繁体中文
        /// </summary>
        //public static string ToTChinese(string str)
        //{
        //    return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0);
        //}

        #endregion

        #region 文件读写、上传、目录操作
        /// <summary>
        /// 读文件内容到stringbuilder
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="Encord">编码  0=gb ；其他为utf8</param>
        /// <returns></returns>
        public static System.Text.StringBuilder ReadFile(string path, string Encord)
        {
            Encoding ED = System.Text.Encoding.GetEncoding(936);
            if (Encord != "0")
                ED = Encoding.UTF8;
            System.Text.StringBuilder Sb = new System.Text.StringBuilder();
            string Paths = System.Web.HttpContext.Current.Server.MapPath(path);
            StreamReader sr = new StreamReader(Paths, ED);
            string str = "";
            while ((str = sr.ReadLine()) != null)
            {
                Sb.Append(str + "\n");
            }
            sr.Close();
            return Sb;
        }

        /// <summary>
        /// 保存stringbuilder到文件
        /// </summary>
        /// <param name="fText">文件内容</param>
        /// <param name="fName">文件名，相对路径</param>
        /// <param name="Encord">编码 0=gb;其他为utf8</param>
        /// <returns></returns>
        public static bool saveFile(System.Text.StringBuilder fText, string fName, string Encord)
        {
            Encoding ED = Encoding.GetEncoding(936);
            if (Encord != "0")
                ED = Encoding.UTF8;
            try
            {
                string paths = System.Web.HttpContext.Current.Server.MapPath(fName);
                StreamWriter sw = new StreamWriter(paths, false, ED);

                sw.Write(fText.ToString());
                sw.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="files">文件框名称</param>
        /// <param name="paths">上传文件路径，url</param>
        /// <param name="fmax">文件的最大值，单位为字节</param>
        /// <param name="ftype">类型：1表示图片；0表示所有文件</param>
        /// <returns></returns>
        public static string upfiles(System.Web.UI.HtmlControls.HtmlInputFile files, string paths, long fmax, string ftype)
        {

            //files 文件上传组件的名称；paths 要上传到的目录;fmax是上传文件最大值；ftype是上传文件的类型
            //默认上传文件最大值100k,文件类型为所有文件
            //1为图片jpg or gif；0为所有文件
            //如果文件大于设定值，返回代码0
            //如果文件类型错误，返回代码1
            //初始化
            long fileMax = 100000;
            string fileType = "0";
            string fileTypet = "";

            fileMax = fmax;
            fileType = ftype;



            if (files.PostedFile.ContentLength > fileMax)
            {
                return "0";
                //返回错误代码，结束程序
            }

            fileTypet = System.IO.Path.GetExtension(files.PostedFile.FileName);
            if (fileType == "1")
            {
                if (fileTypet != ".jpg" && fileTypet != ".JPG" && fileTypet != ".gif" && fileTypet != ".GIF")
                {
                    return "1";
                    //返回错误代码，结束程序
                }
            }
            string destdir = System.Web.HttpContext.Current.Server.MapPath(paths);
            string filename = RandomWord() + fileTypet;
            string destpath = System.IO.Path.Combine(destdir, filename);

            //检查是否有名称重复,如果重复就在前面加从0开始的数字
            int i = 0;
            string tempfilename = filename;
            while (System.IO.File.Exists(destpath))
            {
                //有重复
                tempfilename = i.ToString() + filename;
                destpath = System.IO.Path.Combine(destdir, tempfilename);
                i = i + 1;
            }


            //没有重复，保存文件
            files.PostedFile.SaveAs(destpath);
            //返回文件名称
            return tempfilename;
        }


        /// <summary>
        /// 重建指定的目录如果目录存在，则先删除
        /// </summary>
        /// <param name="Dirs">相对目录</param>
        /// <returns></returns>
        public static bool ReCreateDirectory(string Dirs)
        {
            try
            {
                Dirs = System.Web.HttpContext.Current.Server.MapPath(Dirs);
                if (Directory.Exists(Dirs))
                    Directory.Delete(Dirs);
                Directory.CreateDirectory(Dirs);
                return true;
            }
            catch
            {
                return true;
            }
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="havefile"></param>
        /// <returns></returns>
        public static bool FileIsExist(string havefile)
        {
            havefile = System.Web.HttpContext.Current.Server.MapPath(havefile);
            if (File.Exists(havefile))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 如果目录不存在，则建立之
        /// </summary>
        /// <param name="Dirs">目录相对路径</param>
        /// <returns></returns>
        public static bool CreateDirectory(string Dirs)
        {
            try
            {
                Dirs = System.Web.HttpContext.Current.Server.MapPath(Dirs);
                if (!Directory.Exists(Dirs))
                    Directory.CreateDirectory(Dirs);
                return true;
            }
            catch
            {
                return true;
            }
        }

        /// <summary>
        /// 拷贝指定目录中的所有文件
        /// </summary>
        /// <param name="SDirectory">源目录</param>
        /// <param name="TDirectory">目的目录</param>
        /// <returns></returns>
        public static bool CopyDirectory(string SDirectory, string TDirectory)
        {
            ReCreateDirectory(TDirectory);
            SDirectory = System.Web.HttpContext.Current.Server.MapPath(SDirectory);
            TDirectory = System.Web.HttpContext.Current.Server.MapPath(TDirectory);

            foreach (string f1 in Directory.GetFiles(SDirectory))
            {
                string mm = f1.Split('\\')[f1.Split('\\').Length - 1];
                File.Copy(f1, TDirectory + "\\" + mm, true);
            }
            return true;
        }
        #endregion

        #region 随机数生成
        //生成随即id
        /// <summary>
        /// 生成随即id
        /// </summary>
        /// <returns>随即id</returns>
        public static string RandomWord()
        {
            int iii;
            string RandWord;
            Random ro = new Random();

            iii = ro.Next(1000, 9999);

            string Smonth = System.DateTime.Now.Month.ToString();
            if (Smonth.Length < 2)
            {
                Smonth = "0" + Smonth;
            }
            string Sday = System.DateTime.Now.Day.ToString();
            if (Sday.Length < 2)
            {
                Sday = "0" + Sday;
            }
            string Shour = System.DateTime.Now.Hour.ToString();
            if (Shour.Length < 2)
            {
                Shour = "0" + Shour;
            }
            string Sminite = System.DateTime.Now.Minute.ToString();
            if (Sminite.Length < 2)
            {
                Sminite = "0" + Sminite;
            }
            string Ssecond = System.DateTime.Now.Second.ToString();
            if (Ssecond.Length < 2)
            {
                Ssecond = "0" + Ssecond;
            }
            RandWord = System.DateTime.Now.Year.ToString() + Smonth + Sday + Shour + Sminite + Ssecond + iii;
            return RandWord;

        }



        /// <summary>
        /// 生成随即字符串
        /// </summary>
        /// <param name="sm">获取个数</param>
        /// <returns>结果级被，分开的字符串</returns>
        public static string RandomWord(int sm)
        {
            int iii;
            string RandWord = "";
            Random ro = new Random();



            string Smonth = System.DateTime.Now.Month.ToString();
            if (Smonth.Length < 2)
            {
                Smonth = "0" + Smonth;
            }
            string Sday = System.DateTime.Now.Day.ToString();
            if (Sday.Length < 2)
            {
                Sday = "0" + Sday;
            }
            string Shour = System.DateTime.Now.Hour.ToString();
            if (Shour.Length < 2)
            {
                Shour = "0" + Shour;
            }
            string Sminite = System.DateTime.Now.Minute.ToString();
            if (Sminite.Length < 2)
            {
                Sminite = "0" + Sminite;
            }
            string Ssecond = System.DateTime.Now.Second.ToString();
            if (Ssecond.Length < 2)
            {
                Ssecond = "0" + Ssecond;
            }

            for (int j = 0; j < sm; j++)
            {
                iii = ro.Next(1000, 9999);
                if (RandWord == "")
                {
                    RandWord = RandWord + System.DateTime.Now.Year.ToString() + Smonth + Sday + Shour + Sminite + Ssecond + iii;
                }
                else
                {
                    RandWord = RandWord + "," + System.DateTime.Now.Year.ToString() + Smonth + Sday + Shour + Sminite + Ssecond + iii;
                }

            }
            return RandWord;

        }
        #endregion

        #region  cookie相关操作
        /// <summary>
        /// 返回单值cookie 的值
        /// </summary>
        /// <param name="CookieName"></param>
        /// <returns></returns>
        public static string GetCookies(string CookieName)
        {
            try
            {
                return System.Web.HttpContext.Current.Request.Cookies[CookieName].Value;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 返回多值cookie的某一个值
        /// </summary>
        /// <param name="CookieName">cookie名字</param>
        /// <param name="KeyName">值名字</param>
        /// <returns></returns>
        public static string GetCookies(string CookieName, string KeyName)
        {
            try
            {
                return System.Web.HttpContext.Current.Request.Cookies[CookieName].Values[KeyName].ToString();
            }
            catch
            {
                return "";
            }
        }

        #endregion

        #region 录入数据检测
        /// <summary>
        /// 是否是数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumber(string str)
        {
            Regex r = new Regex("[0-9]{1,}");
            if (r.IsMatch(str))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsValidEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {

            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        /// <summary>
        /// 清理字符串
        /// </summary>
        public static string CleanInput(string strIn)
        {
            return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
        }

        #endregion

        #region 生成静态页面
        /// <summary>
        /// urls生成静态html
        /// </summary>
        public void transHtml(string path, string outpath)
        {
            Page page = new Page();
            StringWriter writer = new StringWriter();
            page.Server.Execute(path, writer);
            FileStream fs;
            if (File.Exists(page.Server.MapPath("") + "\\" + outpath))
            {
                File.Delete(page.Server.MapPath("") + "\\" + outpath);
                fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
            }
            else
            {
                fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
            }
            byte[] bt = Encoding.Default.GetBytes(writer.ToString());
            fs.Write(bt, 0, bt.Length);
            fs.Close();
        }

        #endregion

        #region 获取客户端IP地址
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        #endregion
        #region 将object类型转为datetime，主要是把NULL或空值转成当前日期
        /// <summary>
        /// NULL或空值转成当前日期
        /// </summary>
        /// <returns></returns>
        public static DateTime ObjToDate(object obj1, DateTime sDefault)
        {

            if (obj1 == DBNull.Value || Convert.ToString(obj1) == "")
                return sDefault;
            else
                return Convert.ToDateTime(obj1);

        }
        public static DateTime ObjToDate(object oValue)
        {
            return ObjToDate(oValue, DateTime.Today);
        }
        #endregion
        public static DateTime StrToDate(string str)
        {
            try
            {
                return DateTime.Parse(str);
            }
            catch
            {
                return DateTime.Today;
            }
        }
        #region 将obj类型转为str，主要是把NULL转成默认值
        public static string ObjToStr(object oValue, string sDefault)
        {
            if (oValue == null)
                return sDefault;
            return StrToStr(oValue.ToString(), sDefault);
        }
        public static string ObjToStr(object oValue)
        {
            return ObjToStr(oValue, "");
        }
        #endregion
        #region 将str类型转为str，主要是把NULL转成默认值
        public static string StrToStr(string sValue, string sDefault)
        {
            if (sValue == null)
                return sDefault;
            return sValue;
        }
        public static string StrToStr(string sValue)
        {
            return StrToStr(sValue, "");
        }
        #endregion
        #region 将string类型转为decimal，主要是把NULL转成默认值
        public static decimal StrToDecimal(string sValue, decimal dDefault)
        {
            if (sValue == null || sValue.Length <= 0)
                return dDefault;
            if (!CheckDecimal(sValue))
                return dDefault;
            return Decimal.Parse(sValue);
        }
        public static decimal StrToDecimal(string sValue)
        {
            return StrToDecimal(sValue, 0);
        }
        #endregion
        #region  将object类型转为decimal，主要是把NULL转成默认值
        public static decimal ObjToDecimal(object oValue, decimal dDefault)
        {
            if (oValue == null)
                return dDefault;
            return StrToDecimal(oValue.ToString(), dDefault);
        }
        public static decimal ObjToDecimal(object oValue)
        {
            return ObjToDecimal(oValue, 0);
        }
        #endregion
        #region  检查是否是Decimal的类型
        private static bool CheckDecimal(string sValue)
        {
            int nLen = sValue.Length;
            for (int i = 0; i < nLen; i++)
            {
                if (!char.IsNumber(sValue, i) && sValue[i].CompareTo('-') != 0 && sValue[i].CompareTo('.') != 0)
                    return false;
            }
            return true;
        }
        #endregion
        #region  将object类型转为Int，主要是把NULL转成默认值
        public static int ObjToInt(object oValue, int nDefault)
        {
            if (oValue == null)
                return nDefault;
            return StrToInt(oValue.ToString(), nDefault);
        }
        public static int ObjToInt(object oValue)
        {
            return ObjToInt(oValue, 0);
        }
        //********将string类型转为int，主要是把NULL转成默认值********
        public static int StrToInt(string sValue, int nDefault)
        {
            if (sValue == null || sValue.Length <= 0)
                return nDefault;
            if (!CheckNumber(sValue))
                return nDefault;
            return Int32.Parse(sValue);
        }
        public static int StrToInt(string sValue)
        {
            return StrToInt(sValue, 0);
        }
        private static bool CheckNumber(string sValue)
        {
            int nLen = sValue.Length;
            for (int i = 0; i < nLen; i++)
            {
                if (!char.IsNumber(sValue, i) && sValue[i].CompareTo('-') != 0)
                    return false;
            }
            return true;
        }
        #endregion

        #region str1传进去true返回1,false返回0
        public static int IsTrue(string str1)
        {
            if (str1.Trim().ToUpper() == "TRUE")
                return 1;
            else
                return 0;
        }
        #endregion
        #region 设置ListControl选中的值
        /// <summary>
        /// 设置listcontrol
        /// </summary>
        /// <param name="lc"></param>
        /// <param name="dat"></param>
        /// <param name="cvalue"></param>
        public static void SetListControl(ListControl lc, List<dropdowndata> dat, string cvalue)
        {
            lc.DataSource = dat;
            lc.DataValueField = "Key";
            lc.DataTextField = "Value";
            lc.DataBind();
            lc.SelectedValue = cvalue;
        }
        public static void SetListControlSelected(ListControl lc, string selectedValue, string delimStr)
        {
            foreach (ListItem li in lc.Items)
            {
                li.Selected = false;
            }
            string[] value = selectedValue.Split(Convert.ToChar(delimStr));
            for (int i = 0; i < value.Length; i++)
            {
                for (int j = 0; j < lc.Items.Count; j++)
                {
                    if (lc.Items[j].Value == value[i].ToString() )
                    {
                        lc.Items[j].Selected = true;
                    }
                }
            }   
        }
        #endregion
        #region 设置ListControl选中的值
        public static string GetListControlSelected(ListControl lc, string delimStr)
        {
            string ret = "";
            //循环接收   
            if (lc.Items.Count > 0)   
            {
                for (int i = 0; i < lc.Items.Count; i++)
                {
                    if (lc.Items[i].Selected)
                    {
                        ret = ret + lc.Items[i].Value + delimStr;
                    }
                }
            }   
            return ret;
        }
        #endregion
        #region 给ListControl增加值, (适用于DropDownList, RadioButtonList, CheckBoxList)
        public static void AddListItems(ListControl list, DataTable dt, string sValueFieldName, string sTextFieldName)
        {
            AddListItems(list, dt, sValueFieldName, sTextFieldName, true);
        }
        public static void AddListItems(ListControl list, DataTable dt, string sValueFieldName, string sTextFieldName, bool bClear)
        {
            if (list == null || dt == null)
                return;
            if (sValueFieldName == null || sTextFieldName == null)
                return;
            if (sValueFieldName.Length <= 0 || sTextFieldName.Length <= 0)
                return;

            if (bClear)
                list.Items.Clear();

            int nCount = dt.Rows.Count;
            if (nCount <= 0)
                return;

            string sValue, sText;
            for (int nIndex = 0; nIndex < nCount; nIndex++)
            {
                sValue = ObjToStr(dt.Rows[nIndex][sValueFieldName]);
                sText = ObjToStr(dt.Rows[nIndex][sTextFieldName]);
                list.Items.Add(new ListItem(sText, sValue));
            }
            if (list.Items.Count > 0)
                list.SelectedIndex = 0;
        }
        public static void AddListItems(ListControl list, Hashtable ht, bool bClear)
        {
            if (list == null || ht == null)
                return;
            if (bClear)
                list.Items.Clear();
            list.DataSource = ht;
            list.DataTextField = "value";
            list.DataValueField = "key";
            list.DataBind();
            list.SelectedIndex = 0;
        }
        #endregion
        #region  文件下载
        /// <summary>
        /// 生成excel文件并下载
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="filename">文件名，没有为空</param>
        public static void CreateEXCEL(DataTable dt, string filename)
        {
            if (filename == "")
                filename = "hubs1.xls";
            HttpResponse resp;
            resp = System.Web.HttpContext.Current.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename="+filename);
            string colHeaders = "", ls_item = "";
            int i = 0;

            for (i = 0; i < dt.Columns.Count; i++)
            {
                colHeaders += dt.Columns[i].Caption.ToString() + "\t";
            }
            colHeaders += "\n";
            resp.Write(colHeaders);
            foreach (DataRow row in dt.Rows)
            {
                for(int j=0;j<dt.Columns.Count;j++)
                   ls_item += row[j].ToString() + "\t";
                
                ls_item += "\n";
                resp.Write(ls_item);
                ls_item = "";
            }
            resp.End();
        }

        /// <summary>
        /// 生成文本文件并下载
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="filename">文件名</param>
        public static void CreateTXT(DataTable dt, string filename)
        {
            if (filename == "")
                filename = "hubs1.txt";

            int i = 0;
            StringBuilder txt = new StringBuilder();

            for (i = 0; i < dt.Columns.Count; i++)
            {
                txt.Append(dt.Columns[i].Caption.ToString() + "\t");
            }
            txt.Append("\r\n");

            foreach (DataRow row in dt.Rows)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                    txt.Append(row[j].ToString() + "\t");

                txt.Append("\r\n");
            }

            ///////////////////////////
            byte[] buffer = System.Text.Encoding.Default.GetBytes(txt.ToString());
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;FileName=" + filename);
            System.Web.HttpContext.Current.Response.BinaryWrite(buffer);
            System.Web.HttpContext.Current.Response.End();
        }
        #endregion
        #region 文本内容上传
        /// <summary>
        /// 上传文本文件并且返回内容
        /// </summary>
        /// <param name="file1">文件框</param>
        /// <returns></returns>
        public static string UpdateFileTxt(System.Web.UI.HtmlControls.HtmlInputFile file1)
        {
            if (file1.PostedFile != null && file1.PostedFile.ContentLength > 0)
            {
                System.Web.HttpContext.Current.Response.Clear();
                System.IO.StreamReader sr = new System.IO.StreamReader(file1.PostedFile.InputStream, System.Text.Encoding.GetEncoding(936));
                string s = sr.ReadToEnd();
                sr.Close();

                return s;
            }
            else
            {
                return "";
            }
        }
       
        #endregion
        #region  去掉前后位置多余的逗号
        public static string CutComma(string list)
        {
            return CutSymbol(list, ",");
        }

        public static string CutSymbol(string list, string symbol)
        {
            if (Convert.ToString(list) == "")
                return "";

            string ret = list;
            if (ret.Substring(0, symbol.Length).CompareTo(symbol) == 0)
                ret = ret.Substring(symbol.Length, ret.Length - symbol.Length);
            if (ret.Substring(ret.Length - symbol.Length, symbol.Length).CompareTo(symbol) == 0)
                ret = ret.Substring(0, ret.Length - symbol.Length);
            return ret;
        }
        #endregion

        #region  获取页面传递值
        /// <summary>
        /// 返回数字类型的参数
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static int RequestNumber(string parm)
        {
            try
            {
                return Convert.ToInt32((System.Web.HttpContext.Current.Request.Params[parm]));
            }
            catch
            {
                return 0;
            }
        }
        /// <summary>
        /// 返回字符类型的参数
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static string RequestString(string parm)
        {
            try
            {
                return System.Web.HttpContext.Current.Request[parm].ToString();
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 发送邮件
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="from">发件人邮箱</param>
        /// <param name="sendto">收件人邮箱</param>
        /// <param name="subject">标题</param>
        /// <param name="detail">内容</param>
        /// <param name="html">是否为html格式</param>
        /// <param name="encod">编码</param>
        /// <returns></returns>
        public static bool sendemail(string from,string sendto,string subject,string detail,bool html,Encoding encod)
        {
            if (from == "")
                from = GetValue("mailfrom");
            System.Net.Mail.SmtpClient client = new SmtpClient(GetValue("mailserver"));
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(GetValue("mailuser"), GetValue("mailpwd"));
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            MailAddress MailFrom = new MailAddress(from);
            System.Net.Mail.MailMessage message = new MailMessage();
            System.Net.Mail.MailMessage messageUTF = new MailMessage();

            message.From = MailFrom;
            
            message.To.Add(sendto);
           
            message.Subject = subject;
            message.Body = detail;
            message.Priority = MailPriority.High;

            message.BodyEncoding = encod;
            message.IsBodyHtml = html;
            client.Send(message);
            return true;
        }

        #endregion

        #region 读写 cache
        /// <summary>
        /// 新建cache
        /// </summary>
        /// <param name="CacheName">cache 名字</param>
        /// <param name="obj">cache 对象</param>
        /// <param name="CacheTimes">缓存时间，单位小时</param>
        public static void NewCache(string CacheName, object obj,double CacheTimes)
        {
            System.Web.HttpContext.Current.Cache.Insert(CacheName, obj, null, DateTime.Now.AddHours(CacheTimes), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
        }

        /// <summary>
        /// 获得cache
        /// </summary>
        /// <param name="CacheName">cache 名字</param>
        /// <returns></returns>
        public static object GetCache(string CacheName)
        {
            return System.Web.HttpContext.Current.Cache[CacheName];
        }
        #endregion
        #region 获取Web.Config的值
        private static string GetValue(string name)
        {
            try
            {
                return ConfigurationManager.AppSettings.Get(name);
            }
            catch { return ""; }
        }
        public static int PageSize
        {
            get
            {
                return int.Parse(GetValue("gvpagesize").Trim());
            }
        }
        #endregion

        /// <summary>
        /// 初始化年度下拉框、开始年 2008
        /// </summary>
        /// <param name="ddl"></param>
        public static void inityear(DropDownList ddl)
        {
            ddl.Items.Clear();
            int startyear = 2008;
            int endyear = DateTime.Now.Year;
            for (int i = startyear; i <= endyear; i++)
            {
                ddl.Items.Add(new ListItem(i.ToString(),i.ToString()));
            }
        }

        /// <summary>
        /// sql 过滤
        /// </summary>
        /// <param name="mychar"></param>
        /// <returns></returns>
        public static string VerifySQL(string mychar)
        {
            mychar = mychar.Replace("\"", "'");
            mychar = mychar.Replace("'", "''");
            mychar = mychar.Replace("select", "seletc");
            mychar = mychar.Replace("delete", "deleet");
            mychar = mychar.Replace("update", "updaet");
            mychar = mychar.Replace("declare", "declaer");
            mychar = mychar.Replace("&", "※");
            mychar = mychar.Replace("=", "＝");
            mychar = mychar.Replace("!", "！");
            mychar = mychar.Replace("%", "％");

            return mychar;
        }

        /// <summary>
        /// 去掉首尾多余的分隔逗号
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public static string getidlist(string idlist)
        {
            string[] strlist = idlist.Split(',');
            string rstr = "";
            foreach (string str in strlist)
                if (str != "")
                    rstr = (rstr != "") ? rstr + "," + str : str;
            return rstr;
        }
    }
}